//
//  GGFilterManager.m
//  视频录制实时切换滤镜
//
//  Created by 聚点互动iOS on 2020/12/28.
//

#import "GGFilterManager.h"

@implementation GGFilterManager

static GGFilterManager *_manager;
// 单例
+(instancetype)manager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[GGFilterManager alloc] init];
        
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Materials" ofType:@"plist"]];
        
        NSArray<NSDictionary *> *defaults = [dict valueForKey:@"defaults"];
        NSArray<NSDictionary *> *defines = [dict valueForKey:@"defines"];
        
        NSMutableArray *defaultModels = [NSMutableArray array];
        [defaults enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [defaultModels addObject:[GGFilterMaterialModel instanceWithDict:obj]];
        }];
        NSMutableArray *defineModels = [NSMutableArray array];
        [defines enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [defineModels addObject:[GGFilterMaterialModel instanceWithDict:obj]];
        }];
        _manager.defaults = defaultModels;
        _manager.defines = defineModels;
    });
    return _manager;
}




/// 通过滤镜 ID 返回滤镜对象
/// @param filterID 滤镜 ID
- (GPUImageFilter *)filterWithFilterID:(NSString *)filterID{
    __block GGFilterMaterialModel *filterMaterialModel;
    [self.defaults enumerateObjectsUsingBlock:^(GGFilterMaterialModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.filter_id isEqual:filterID]) {
            filterMaterialModel = obj;
            *stop = YES;
        }
    }];
    if (!filterMaterialModel) {
        [self.defines enumerateObjectsUsingBlock:^(GGFilterMaterialModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.filter_id isEqual:filterID]) {
                filterMaterialModel = obj;
                *stop = YES;
            }
        }];
    }
    if (!filterMaterialModel) {
        return nil;
    }
    return [NSClassFromString(filterMaterialModel.filter_class) new];
}

@end
